<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Company;
use App\Models\Member;
use App\Models\User;
use App\Models\Wages;
use App\Models\WagesUpload;
use App\Services\AppUser;
use App\Http\Requests\AdminPost;
use App\Services\ValidatorService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Monolog\Logger;
use Services\HandleDataService;
use Tymon\JWTAuth\JWTAuth;
use App\Services\ExcelExportService;
use Psr\Log\LoggerInterface;

/**
 * Class ExcelController
 * @package App\Http\Controllers
 */
class ExcelController extends BaseController
{
    public $serviceName = ExcelExportService::class;

    private $logger;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    public function export()
    {
        if ($this->logger) {
            $this->logger->info('Doing work');
        }
        $this->logger->error('Oh no!', array('exception' => 111));

        try {
            $directory = storage_path('excel') . '/export';
            $fileName = rand(1000, 9999) . time() . ".xlsx";//导出文件名
            $header = ['user_id' => '销售名称', 'name' => '客户名称'
            ];
            $widthArray = ['A' => 30, 'B' => 30, 'C' => 30, 'D' => 50, 'E' => 50];
            $dataBuild = User::query();
            $service = new ExcelExportService();
            $service->exportDataBySheet($directory, $fileName, $dataBuild, $header, '', 1000, $widthArray);
            return response()->download($directory . '/' . $fileName, '导出文件.xlsx', $headers = ['Content-Type' => 'application/zip;charset=utf-8']);
        } catch (\ Exception $exception) {
            echo $exception->getMessage();
            die;
            throw new AppException('export_fail');

        }
        return $this->success(['$user']);
    }

    public function import(Request $request)
    {
        ini_set('memory_limit','1024M');

        //在源生的php代码中是使用$_FILE来查看上传文件的属性
        //但是在laravel里面有更好的封装好的方法，就是下面这个
        //显示的属性更多
        $fileCharater = $request->file('file');
        $params = $request->all();
        $type = 1;//月结
        if (isset($params['type'])){
            $type = $params['type'];
        }

        if (!isset($params['month']) || empty($params['month'])) {
            return $this->errorCode('10001', [], '月份不能为空');
        }

        if (!isset($params['year']) || empty($params['year'])) {
            return $this->errorCode('10001', [], '年份不能为空');
        }

        if ((!isset($params['company_id']) || empty($params['company_id']))  && $type == 1) {
            return $this->errorCode('10001', [], '公司id不能为空');
        }
        $day = $params['day'];
        if ($type == 1){
            $company = Company::query()->where('c_id', $params['company_id'])->first();
            if (!$company) {
                return $this->errorCode('10001', [], '公司不存在');
            }
        }else{
            $company = ['c_id' => 0, 'name' => ''];
        }


        $month = $params['month'];
        $success_num = $error_num = 0;

        $headerMap = [
            '姓名' => 'name',
            '身份证号' => 'id_card',
            '电话号码' => 'mobile',
        ];
        try {

            if ($fileCharater->isValid()) { //括号里面的是必须加的哦
                //如果括号里面的不加上的话，下面的方法也无法调用的

                //获取文件的扩展名
                $ext = $fileCharater->getClientOriginalExtension();

                if (!in_array($ext, ['xlsx', 'xls'])) {
                    throw new AppException('import_type_is_fail');
                }

                $originName = $fileCharater->getClientOriginalName();

                //获取文件的绝对路径
                $path = $fileCharater->getRealPath();

                //定义文件名
                $filename = date('Y-m-d-H-i-s') . '.' . $ext;

                //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
                $result = Storage::disk('public')->put($filename, file_get_contents($path));

                $directory = storage_path('app') . '/public';

                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
                # 打开文件、载入excel表格
                $spreadsheet = $reader->load($directory . '/' . $filename);
                # 获取活动工作薄
                $sheet = $spreadsheet->getActiveSheet();

                # 获取总列数
                $highestColumn = $sheet->getHighestColumn();
                # 获取总行数
                $highestRow = $sheet->getHighestRow();
                # 列数 改为数字显示
                $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);


                $result = WagesUpload::query()->create([
                    'path' => $directory . '/' . $filename,
                    'content' => $originName,
                    'company_id' => $company['c_id'],
                    'company_name' => $company['name'],
                    'year' => $params['year'],
                    'day' => $params['day'],
                    'month' => $month
                ]);
                $id = $result->getQueueableId();


                for ($a = 1; $a <= $highestRow; $a++) {
                    $i = 0;
                    $row_data = [];
                    for ($column = 1; $column <= $highestColumnIndex; $column++) {
                        $cell = $sheet->getCellByColumnAndRow($column, $a);
                        $cellValue = $cell->getValue();
                        // 处理日期格式的单元格
                        if (\PhpOffice\PhpSpreadsheet\Shared\Date::isDateTime($cell)) {
                            $cellValue = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue)
                                ->format('Y-m-d');
                        }
                        $row_data[]  = $cellValue;;
                        $i++;
                    }
                    if (!implode('', $row_data)) {
                        //删除空行
                        continue;
                    }
                    if ($a == 1) {
                        $headerColumn = $row_data;
                        continue;
                    }

                    $info = [];
                    $json = [];
                    foreach ($row_data as $key => $value) {
                        if (isset($headerMap[$headerColumn[$key]])) {
                            $info[$headerMap[$headerColumn[$key]]] = $value;
                        } else {
                            $json[$headerColumn[$key]] = $value;
                        }
                    }
                    $info['json'] = json_encode($json, JSON_UNESCAPED_UNICODE);
                    $info['header_json'] = json_encode($headerColumn, JSON_UNESCAPED_UNICODE);
                    $info['aid'] = $id;
                    $info['month'] = $month;
                    $info['year'] = $params['year'];
                    $info['day'] = $params['day'];
                    $info['type'] = $type;
                    $info['company_id'] = $company['c_id'];
                    $info['company_name'] = $company['name'];
                    Wages::query()->create($info);
                }
            }

            WagesUpload::query()->where('aid', $id)->update(['is_success' => 1]);
            $data['success_num'] = $success_num;
            $data['error_num'] = $error_num;
            return $this->success($data);

        } catch (\ Exception $exception) {
            $this->logger->error('Oh no!', array('exception' => $exception->getMessage()));
            return $this->error($exception->getMessage());
            throw new AppException($exception->getMessage());

        }
    }


}
